package com.test.demo.nettydemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.util.CharsetUtil;

import java.util.Scanner;

public class NettyClient {
    public static void main(String[] args) {
        //接收连接请求
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        //接受其他读写请求
        try {
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(bossGroup)//绑定两个线程
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast("decoder",new ByteArrayDecoder());
                            socketChannel.pipeline().addLast("encoder",new ByteArrayEncoder());
                            socketChannel.pipeline().addLast(new HelloClientHandler());
                        }
                    });
            System.out.println("客户端启动成功");

            ChannelFuture cf = bootstrap.connect("127.0.0.1",9000).sync();
            Scanner scanner = new Scanner(System.in);

            while (true){
                String s = scanner.nextLine();
                if ("exit".equals(s)){
                    break;
                }else{
                    ByteBuf buf = Unpooled.copiedBuffer(s, CharsetUtil.UTF_8);
                    cf.channel().writeAndFlush(buf);
                }
            }

            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
        }
    }
}
